﻿#include <iostream>
#include <thread>
#include "MQTTClient.h"
#include <thread>
#include <mutex>
using namespace std;
mutex mtx;

int main()
{
	string ip = "ndddbda0.ala.cn-hangzhou.emqxsl.cn";
	int port = 8883;
	string username = "admin";
	string password = "admin";
	string crtfile = "emqxsl-ca.crt";

	cout << "MQTT client start listening..." << endl;

	MQTTClient client(ip, port, username, password, crtfile);
	client.subscribe("test");
	client.start();
	string msg = "";
	string msg_old = "";
	string msg_old1 = "";

	thread t([&client,&msg ,&msg_old1]()->void {
		while (msg!="stop") {
			if (msg != msg_old1) {
				
				cout <<"Send Msg:\t"<< msg << endl;
				client.publish("test",msg);
				msg_old1 = msg;
			}
			
			this_thread::sleep_for(chrono::seconds(1));
		}
	});
	t.detach();
	while (msg != "stop") {
		msg = client.getLastMessage();
		if (msg != msg_old) {
			cout <<"Receive Msg:\t" << msg << endl;
			msg_old = msg;
		}
		this_thread::sleep_for(chrono::seconds(1));
	}
	
}

